﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace ForumLibrary
{
    public class hashEncode
    {
        /// <summary>
        /// convert byte[] returned from SHA1 to string
        /// encode type {1  - decimal, 2 - hex, 3 - Base64 }
        /// </summary>
        /// <param name="arrInput">byte arr</param>
        /// <param name="encode">encode type</param>
        /// <returns></returns>
        public string ByteArrayToString(byte[] arrInput, int encode)
        {
            int i;
            StringBuilder Output = new StringBuilder(arrInput.Length);
            if (3 == encode)
            {
                return Convert.ToBase64String(arrInput);
            }
            for (i = 0; i < arrInput.Length; i++)
            {
                switch (encode)
                {
                    case 1:
                        //encode to decimal with 3 digits so 7 will be 007 (as range of 8 bit is 127 to -128)
                        Output.Append(arrInput[i].ToString("D3"));
                        break;
                    case 2:
                        Output.Append(arrInput[i].ToString("X2"));
                        break;
                }
            }
            return Output.ToString();
        }

        /// <summary>
        /// hashing string password from user
        /// </summary>
        /// <param name="tPass">password string</param>
        /// <returns></returns>
        public string HashEncode(string tPass)
        {
            SHA1 a = new SHA1CryptoServiceProvider();
            byte[] arr = new byte[60];
            string hash = "";
            arr = a.ComputeHash(Encoding.UTF8.GetBytes(tPass));
            hash = ByteArrayToString(arr, 2);//encode type hex
            return hash;
        }


    }
}
